﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace sydfdl.TMS.BLL
{
    /// <summary>
    /// 底层操作类
    /// </summary>
    public abstract class SqlHelper
    {
        //数据库连结字符串
        public static readonly string tmsConn = ConfigurationManager.ConnectionStrings["tmsConn"].ConnectionString;

        /// <summary>
        /// 哈希表缓存
        /// </summary>
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// 执行命令,返回影响行数:传入连结字符串
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// 执行命令,返回影响行数：传入连结对象
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 执行命令,返回影响行数：传入回滚对象
        /// </summary>
        /// <param name="trans"></param>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 读出数据库：传入连结字符串
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                //datareader对象关闭时，关联的connection也将关闭
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        /// <summary>
        /// 运行sql语句，结果返回到DataSet中
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="cmdText"></param>
        /// <returns></returns>
        public static DataSet ExecuteSqlToDataSet(string connectionString, string cmdText)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            try
            {
                adapter.Fill(ds);
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
            }

            return ds;
        }

        /// <summary>
        /// 运行sql语句，结果返回到DataSet中
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataSet ExecuteSqlToDataSet(string connectionString, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Parameters.Clear();
            foreach (SqlParameter parameter in commandParameters)
            {
                cmd.Parameters.Add(parameter);
            }
            SqlConnection conn = new SqlConnection(connectionString);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            try
            {
                adapter.Fill(ds);
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
            }

            return ds;
        }

        /// <summary>
        /// 返回首行首行：传入连结字符串
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// 返回首行首行：传入连结对象
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 加入缓存参数
        /// </summary>
        /// <param name="cacheKey">键</param>
        /// <param name="cmdParms">缓存参数数组</param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// 键值对查找缓存参数
        /// </summary>
        /// <param name="cacheKey">键</param>
        /// <returns>参数数组</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }

        /// <summary>
        /// 命令过程
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="conn"></param>
        /// <param name="trans"></param>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="cmdParms"></param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandTimeout = 150;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        #region 自定义

        /// <summary>
        /// 读出数据库,SQL脚本
        /// </summary>
        /// <param name="cmdText">sql脚本</param>
        /// <param name="commandParameters">参数</param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReaderText(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteReader(tmsConn, CommandType.Text, cmdText, commandParameters);
        }

        /// <summary>
        /// 读出数据库,存储过程
        /// </summary>
        /// <param name="cmdText">sql StoredProcedure 脚本</param>
        /// <param name="commandParameters">参数</param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReaderStoredProcedure(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteReader(tmsConn, CommandType.StoredProcedure, cmdText, commandParameters);
        }

        /// <summary>
        /// 执行SQL脚本
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static int ExecuteNonQueryText(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteNonQuery(tmsConn, CommandType.Text, cmdText, commandParameters);
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static int ExecuteNonQueryStoredProcedure(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteNonQuery(tmsConn, CommandType.StoredProcedure, cmdText, commandParameters);
        }

        /// <summary>
        /// 执行存储过程,返回DataSet
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>DataSet</returns>
        public static DataSet ExecuteProcedureToDataSet(string storedProcName, SqlParameter[] parameters, string tableName)
        {
            using (SqlConnection connection = new SqlConnection(tmsConn))
            {
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                SqlCommand command = new SqlCommand(storedProcName, connection);
                command.CommandType = CommandType.StoredProcedure;
                if (parameters != null)
                    foreach (SqlParameter parameter in parameters)
                    {
                        if (parameter != null)
                        {
                            // 检查未分配值的输出参数,将其分配以DBNull.Value.
                            if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                                (parameter.Value == null))
                            {
                                parameter.Value = DBNull.Value;
                            }
                            command.Parameters.Add(parameter);
                        }
                    }
                command.CommandTimeout = 180;
                sqlDA.SelectCommand = command;
                DataSet dataSet = new DataSet();
                try
                {
                    sqlDA.Fill(dataSet);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    connection.Close();
                }

                return dataSet;
            }
        }

        #endregion
    }
}
